<template>
  <div class="container">
    <CommentInputView @addComment="addComment" />
    <div style="margin-top: 20px;">
      <el-radio v-model="filterType" :label="1">看全部</el-radio>
      <el-radio v-model="filterType" :label="2">只看自己</el-radio>
    </div>
    <CommentListView :commentList=commentList />
  </div>
</template>

<script setup lang="ts">
import { createCommentService, getCommentListService } from '@/services/comment'
import CommentInputView from './CommentInput.vue'
import CommentListView from './CommentListView.vue'
import { computed, onBeforeMount, provide, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router'


const filterType = ref(1) // 1-看全部  2-只看自己
const commentList = ref([])
const currentUserName = computed(() => window.sessionStorage.getItem('currentUserName'))

// 获取列表
async function getCommentList() {
  const responseModel = await getCommentListService(filterType.value)
  console.log('comment page getCommentList()==>responseModel\n', responseModel)
  if (!responseModel.ok) {
    alert(responseModel.message)
    return
  }
  commentList.value = responseModel.data

}

async function addComment(content) {
  const responseModel = await createCommentService(content)
  console.log('comment page addComment()==>responseModel\n', responseModel)
  if (!responseModel.ok) {
    ElMessage({ message: responseModel.message, type: 'error', showClose: true })
    return
  }
  commentList.value.unshift(responseModel.data)// unshift() 往数组头部插入一个新元素
}

// 更新留言列表
async function UpdateCommentList(newComment) {
  commentList.value = commentList.value.map(
    item => {
      if (item._id === newComment._id) return newComment
      return item
    }
  )
}


provide('UpdateCommentList', UpdateCommentList) //提供一个方法给后代使用
provide('currentUserName', currentUserName) //当前登录的用户

// 立即执行getCommentList(),当filterType变化时再次执行
watch(filterType, async () => await getCommentList(), { immediate: true })

onBeforeMount(() => {
  if (!currentUserName.value) {
    alert('comment page,请先登录')
    setTimeout(router.push('/login'),100)
  }
})

</script>

<style lang="stylus" scoped>
.container
  margin: 20px 50px 0;

</style>
